﻿ namespace Graph;

public class BFSGraph
{
    private IGraph G;
    private bool[] visited;
    private Queue<int> queue = new Queue<int>();

    public MyList<int> ResultList { get; } = new MyList<int>();

    public BFSGraph(IGraph G)
    {
        this.G = G;
        visited = new bool[G.V];

        for (int v = 0; v < G.V; v++)
        {
            if (!visited[v])
            {
                BFS(v);
            }
        }
    }

    private void BFS(int s)
    {
        visited[s] = true;
        queue.Enqueue(s);

        while (queue.Count != 0)
        {
            int v = queue.Dequeue();
            ResultList.Add(v);

            foreach (int w in G.Adj(v))
            {
                if (!visited[w])
                {
                    visited[w] = true;
                    queue.Enqueue(w);
                }
            }
        }
    }

    //验证
    static void Main(string[] args)
    {
        IGraph graph = new AdjLinkList("图的广度优先遍历/g.txt");
        BFSGraph fSGraph = new(graph);
        Console.WriteLine(fSGraph.ResultList);

        DFSGraph fSGraph2 = new(graph);
        Console.WriteLine(fSGraph2.ResultList);

        Console.Read();
    }
}
